/**
 * 权限管理页面
 * 
 * 功能特性：
 * - 权限列表展示（支持分页、搜索、筛选）
 * - 权限的增删改查操作
 * - 权限分配给角色的功能
 * - 权限详情查看和编辑
 * - 性能优化：最多2-3次渲染，防重复请求，300ms搜索防抖
 * - 主题支持：亮色/暗色主题切换
 * - 响应式设计：适配不同屏幕尺寸
 */

import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Table,
  Card,
  Button,
  Input,
  Space,
  Modal,
  Form,
  Select,
  AutoComplete,
  Tag,
  Tooltip,
  Row,
  Col,
  Divider,
  Typography,
  Alert,
  Popconfirm,
  Badge,

  message
} from 'antd';
import {
  PlusOutlined,

  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,

  EyeOutlined,
  SettingOutlined,
  UserOutlined,
  TeamOutlined
} from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { useTheme } from '../contexts/ThemeContext';
import { showNotification } from '../utils/notification';
import { requestGuard } from '../utils/requestGuard';
import api from '../services/api';

const { Title, Text } = Typography;


// 权限数据接口
interface Permission {
  id: number;
  name: string;
  display_name: string;
  description?: string;
  resource: string;
  action: string;
  is_system: boolean;
  created_at: string;
  updated_at: string;
}

// 角色数据接口
interface Role {
  id: number;
  name: string;
  display_name: string;
  description?: string;
  is_active: boolean;
}

// 权限表单数据接口
interface PermissionFormData {
  name: string;
  display_name: string;
  description?: string;
  resource: string;
  action: string;
}

// 分页配置接口
interface PaginationConfig extends TablePaginationConfig {
  current: number;
  pageSize: number;
  total: number;
}

const PermissionManagement: React.FC = () => {
  const { currentTheme } = useTheme();
  
  // 状态管理
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [resources, setResources] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  
  // 分页配置
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
  });

  // 模态框状态
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isAssignModalVisible, setIsAssignModalVisible] = useState(false);
  const [currentPermission, setCurrentPermission] = useState<Permission | null>(null);
  const [selectedRoles, setSelectedRoles] = useState<number[]>([]);

  // 表单实例
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();


  const permissionsLoadedRef = useRef(false);
  const rolesLoadedRef = useRef(false);
  const resourcesLoadedRef = useRef(false);

  /**
   * 获取权限列表 - 使用requestGuard防止重复请求
   */
  const fetchPermissions = useCallback(async () => {
    // 使用requestGuard防止重复请求
    if (!requestGuard.canRequest('fetchPermissions-list')) {
      return;
    }

    setLoading(true);

    try {

      const response = await api.get('/v1/permissions');
      const data = response.data.data;

      // 直接使用后端返回的过滤数据
      setPermissions(data.permissions);
      setPagination(prev => ({
        ...prev,
        total: data.permissions.length,
      }));

      permissionsLoadedRef.current = true;
    } catch (error: any) {
      console.error('获取权限列表失败:', error);
      showNotification('error', '获取权限列表失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchPermissions-list');
      setLoading(false);
    }
  }, []); // 无依赖项

  /**
   * 获取角色列表 - 用于权限分配
   */
  const fetchRoles = useCallback(async () => {
    if (rolesLoadedRef.current) {

      return;
    }

    if (!requestGuard.canRequest('fetchRoles-for-permission')) {
      return;
    }

    try {

      const response = await api.get('/v1/roles', { 
        params: { page: 1, page_size: 100, is_active: true } 
      });
      setRoles(response.data.data.roles);
      rolesLoadedRef.current = true;
    } catch (error: any) {
      console.error('获取角色列表失败:', error);
      showNotification('error', '获取角色列表失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchRoles-for-permission');
    }
  }, []);

  /**
   * 获取资源类型列表
   */
  const fetchResources = useCallback(async () => {
    if (resourcesLoadedRef.current) {

      return;
    }

    if (!requestGuard.canRequest('fetchResources')) {
      return;
    }

    try {

      const response = await api.get('/v1/permissions/resources');
      setResources(response.data.data);
      resourcesLoadedRef.current = true;
    } catch (error: any) {
      console.error('获取资源类型失败:', error);
      showNotification('error', '获取资源类型失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchResources');
    }
  }, []);



  /**
   * 表格分页处理
   */
  const handleTableChange = useCallback((newPagination: TablePaginationConfig) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current || 1,
      pageSize: newPagination.pageSize || 10,
    }));
  }, []);

  // 组件挂载时获取数据
  useEffect(() => {


    // 清除可能存在的请求防护状态（页面刷新时）
    requestGuard.clearGuard('fetchPermissions');
    requestGuard.clearGuard('fetchRoles');
    requestGuard.clearGuard('fetchResources');

    fetchPermissions();
    fetchRoles();
    fetchResources();

    return () => {
      // 组件卸载时的清理
    };
  }, []); // 空依赖数组，只在挂载时执行一次



  // 获取当前页面的权限数据
  const getCurrentPageData = () => {
    const startIndex = (pagination.current - 1) * pagination.pageSize;
    const endIndex = startIndex + pagination.pageSize;
    return permissions.slice(startIndex, endIndex);
  };



  /**
   * 创建权限
   */
  const handleCreatePermission = async (values: PermissionFormData) => {
    try {
      await api.post('/v1/permissions', values);
      showNotification('success', '创建权限成功');
      setIsCreateModalVisible(false);
      createForm.resetFields();
      permissionsLoadedRef.current = false;
      fetchPermissions();
    } catch (error: any) {
      showNotification('error', '创建权限失败', error.message);
    }
  };

  /**
   * 更新权限
   */
  const handleUpdatePermission = async (values: Partial<PermissionFormData>) => {
    if (!currentPermission) return;

    try {
      await api.put(`/v1/permissions/${currentPermission.id}`, values);
      showNotification('success', '更新权限成功');
      setIsEditModalVisible(false);
      editForm.resetFields();
      setCurrentPermission(null);
      permissionsLoadedRef.current = false;
      fetchPermissions();
    } catch (error: any) {
      showNotification('error', '更新权限失败', error.message);
    }
  };

  /**
   * 删除权限
   */
  const handleDeletePermission = async (permission: Permission) => {
    try {
      await api.delete(`/v1/permissions/${permission.id}`);
      showNotification('success', '删除权限成功');
      permissionsLoadedRef.current = false;
      fetchPermissions();
    } catch (error: any) {
      showNotification('error', '删除权限失败', error.message);
    }
  };

  /**
   * 分配权限给角色
   */
  const handleAssignPermission = async () => {
    if (!currentPermission) return;

    try {
      await api.post(`/v1/permissions/${currentPermission.id}/assign`, {
        role_ids: selectedRoles
      });
      showNotification('success', '权限分配成功');
      setIsAssignModalVisible(false);
      setSelectedRoles([]);
      setCurrentPermission(null);
    } catch (error: any) {
      showNotification('error', '权限分配失败', error.message);
    }
  };

  /**
   * 打开编辑模态框
   */
  const openEditModal = (permission: Permission) => {
    setCurrentPermission(permission);
    editForm.setFieldsValue({
      display_name: permission.display_name,
      description: permission.description,
    });
    setIsEditModalVisible(true);
  };

  /**
   * 打开详情模态框
   */
  const openDetailModal = (permission: Permission) => {
    setCurrentPermission(permission);
    setIsDetailModalVisible(true);
  };

  /**
   * 打开分配模态框
   */
  const openAssignModal = (permission: Permission) => {
    setCurrentPermission(permission);
    setSelectedRoles([]);
    setIsAssignModalVisible(true);
  };

  /**
   * 获取权限状态标签
   */
  const getPermissionStatusTag = (permission: Permission) => {
    if (permission.is_system) {
      return <Tag color="blue">系统权限</Tag>;
    }
    return <Tag color="green">自定义权限</Tag>;
  };

  /**
   * 获取资源颜色
   */
  const getResourceColor = (resource: string): string => {
    const colors = ['magenta', 'red', 'volcano', 'orange', 'gold', 'lime', 'green', 'cyan', 'blue', 'geekblue', 'purple'];
    const index = resource.charCodeAt(0) % colors.length;
    return colors[index];
  };

  // 表格列定义
  const columns: ColumnsType<Permission> = [
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      fixed: 'left',
      render: (text: string, record: Permission) => (
        <Space direction="vertical" size={0}>
          <Text strong>{text}</Text>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            {record.display_name}
          </Text>
        </Space>
      ),
    },
    {
      title: '资源类型',
      dataIndex: 'resource',
      key: 'resource',
      width: 120,
      render: (text: string) => (
        <Tag color={getResourceColor(text)}>{text}</Tag>
      ),
    },
    {
      title: '操作类型',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (text: string) => (
        <Tag color="processing">{text}</Tag>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text || '暂无描述'}>
          <Text type="secondary">{text || '暂无描述'}</Text>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_system',
      key: 'status',
      width: 120,
      render: (_, record: Permission) => getPermissionStatusTag(record),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text: string) => (
        <Text type="secondary">
          {new Date(text).toLocaleString('zh-CN')}
        </Text>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record: Permission) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => openDetailModal(record)}
            />
          </Tooltip>
          {!record.is_system && (
            <>
              <Tooltip title="编辑权限">
                <Button
                  type="text"
                  icon={<EditOutlined />}
                  onClick={() => openEditModal(record)}
                />
              </Tooltip>
              <Tooltip title="删除权限">
                <Popconfirm
                  title="确认删除"
                  description={`确定要删除权限 "${record.display_name}" 吗？`}
                  onConfirm={() => handleDeletePermission(record)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                  />
                </Popconfirm>
              </Tooltip>
            </>
          )}
          <Tooltip title="分配给角色">
            <Button
              type="text"
              icon={<TeamOutlined />}
              onClick={() => openAssignModal(record)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ marginBottom: '16px' }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Title level={4} style={{ margin: 0 }}>
                权限管理
              </Title>
            </Col>
            <Col>
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => setIsCreateModalVisible(true)}
                >
                  新建权限
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={() => {
                    permissionsLoadedRef.current = false;
                    fetchPermissions();
                  }}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </div>



        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: '16px' }}>
          <Col xs={12} sm={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: currentTheme.config.token?.colorPrimary }}>
                  {permissions.length}
                </div>
                <div style={{ color: currentTheme.config.token?.colorTextSecondary }}>总权限数</div>
              </div>
            </Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: currentTheme.config.token?.colorSuccess }}>
                  {permissions.filter(p => p.is_system).length}
                </div>
                <div style={{ color: currentTheme.config.token?.colorTextSecondary }}>系统权限</div>
              </div>
            </Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: currentTheme.config.token?.colorWarning }}>
                  {permissions.filter(p => !p.is_system).length}
                </div>
                <div style={{ color: currentTheme.config.token?.colorTextSecondary }}>自定义权限</div>
              </div>
            </Card>
          </Col>
          <Col xs={12} sm={6}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: currentTheme.config.token?.colorInfo }}>
                  {resources.length}
                </div>
                <div style={{ color: currentTheme.config.token?.colorTextSecondary }}>资源类型</div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 权限表格 */}
        <Table
          columns={columns}
          dataSource={getCurrentPageData()}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
          size="middle"
        />
      </Card>

      {/* 创建权限模态框 */}
      <Modal
        title="新建权限"
        open={isCreateModalVisible}
        onCancel={() => {
          setIsCreateModalVisible(false);
          createForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={createForm}
          layout="vertical"
          onFinish={handleCreatePermission}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="权限名称"
                rules={[
                  { required: true, message: '请输入权限名称' },
                  { pattern: /^[a-zA-Z][a-zA-Z0-9._-]*$/, message: '权限名称格式不正确' }
                ]}
              >
                <Input placeholder="如: user.create" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="display_name"
                label="显示名称"
                rules={[{ required: true, message: '请输入显示名称' }]}
              >
                <Input placeholder="如: 创建用户" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="resource"
                label="资源类型"
                rules={[{ required: true, message: '请输入资源类型' }]}
              >
                <AutoComplete
                  placeholder="选择或输入资源类型"
                  allowClear
                  filterOption={(inputValue, option) =>
                    option?.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                  }
                  options={resources.map(resource => ({
                    value: resource,
                    label: resource
                  }))}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="action"
                label="操作类型"
                rules={[{ required: true, message: '请输入操作类型' }]}
              >
                <AutoComplete
                  placeholder="选择或输入操作类型"
                  allowClear
                  filterOption={(inputValue, option) =>
                    option?.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                  }
                  options={[
                    { value: 'view', label: 'view' },
                    { value: 'create', label: 'create' },
                    { value: 'update', label: 'update' },
                    { value: 'delete', label: 'delete' },
                    { value: 'manage', label: 'manage' },
                    { value: 'execute', label: 'execute' },
                    { value: 'analyze', label: 'analyze' },
                    { value: 'config', label: 'config' },
                    { value: 'monitor', label: 'monitor' },
                    { value: 'log', label: 'log' }
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="description"
            label="权限描述"
          >
            <Input.TextArea
              placeholder="请输入权限描述"
              rows={3}
            />
          </Form.Item>
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setIsCreateModalVisible(false);
                createForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                创建
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑权限模态框 */}
      <Modal
        title="编辑权限"
        open={isEditModalVisible}
        onCancel={() => {
          setIsEditModalVisible(false);
          editForm.resetFields();
          setCurrentPermission(null);
        }}
        footer={null}
        width={600}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleUpdatePermission}
        >
          <Alert
            message="注意"
            description="系统权限的名称、资源类型和操作类型不可修改"
            type="info"
            showIcon
            style={{ marginBottom: '16px' }}
          />
          <Form.Item
            name="display_name"
            label="显示名称"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="请输入显示名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="权限描述"
          >
            <Input.TextArea
              placeholder="请输入权限描述"
              rows={3}
            />
          </Form.Item>
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setIsEditModalVisible(false);
                editForm.resetFields();
                setCurrentPermission(null);
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                更新
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限详情模态框 */}
      <Modal
        title="权限详情"
        open={isDetailModalVisible}
        onCancel={() => {
          setIsDetailModalVisible(false);
          setCurrentPermission(null);
        }}
        footer={[
          <Button key="close" onClick={() => {
            setIsDetailModalVisible(false);
            setCurrentPermission(null);
          }}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {currentPermission && (
          <div>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div>
                  <Text strong>权限名称:</Text>
                  <div style={{ marginTop: '4px' }}>
                    <Text code>{currentPermission.name}</Text>
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <Text strong>显示名称:</Text>
                  <div style={{ marginTop: '4px' }}>
                    <Text>{currentPermission.display_name}</Text>
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <Text strong>资源类型:</Text>
                  <div style={{ marginTop: '4px' }}>
                    <Tag color={getResourceColor(currentPermission.resource)}>
                      {currentPermission.resource}
                    </Tag>
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <Text strong>操作类型:</Text>
                  <div style={{ marginTop: '4px' }}>
                    <Tag color="processing">{currentPermission.action}</Tag>
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <Text strong>权限状态:</Text>
                  <div style={{ marginTop: '4px' }}>
                    {getPermissionStatusTag(currentPermission)}
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <Text strong>创建时间:</Text>
                  <div style={{ marginTop: '4px' }}>
                    <Text type="secondary">
                      {new Date(currentPermission.created_at).toLocaleString('zh-CN')}
                    </Text>
                  </div>
                </div>
              </Col>
              <Col span={24}>
                <div>
                  <Text strong>权限描述:</Text>
                  <div style={{ marginTop: '4px' }}>
                    <Text type="secondary">
                      {currentPermission.description || '暂无描述'}
                    </Text>
                  </div>
                </div>
              </Col>
            </Row>
          </div>
        )}
      </Modal>

      {/* 权限分配模态框 */}
      <Modal
        title="分配权限给角色"
        open={isAssignModalVisible}
        onCancel={() => {
          setIsAssignModalVisible(false);
          setSelectedRoles([]);
          setCurrentPermission(null);
        }}
        onOk={handleAssignPermission}
        width={600}
      >
        {currentPermission && (
          <div>
            <Alert
              message={`正在为权限 "${currentPermission.display_name}" 分配角色`}
              type="info"
              showIcon
              style={{ marginBottom: '16px' }}
            />
            <div style={{ marginBottom: '16px' }}>
              <Text strong>选择角色:</Text>
            </div>
            <Select
              mode="multiple"
              placeholder="请选择要分配的角色"
              value={selectedRoles}
              onChange={setSelectedRoles}
              style={{ width: '100%' }}
              optionLabelProp="label"
            >
              {roles.map(role => (
                <Option key={role.id} value={role.id} label={role.display_name}>
                  <Space>
                    <Badge
                      status={role.is_active ? 'success' : 'default'}
                      text={role.display_name}
                    />
                    <Text type="secondary">({role.name})</Text>
                  </Space>
                </Option>
              ))}
            </Select>
            {selectedRoles.length > 0 && (
              <div style={{ marginTop: '16px' }}>
                <Text strong>已选择的角色:</Text>
                <div style={{ marginTop: '8px' }}>
                  <Space wrap>
                    {selectedRoles.map(roleId => {
                      const role = roles.find(r => r.id === roleId);
                      return role ? (
                        <Tag key={roleId} color="blue">
                          {role.display_name}
                        </Tag>
                      ) : null;
                    })}
                  </Space>
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default PermissionManagement;
